package cn.suchan.jianzhi.sort;

/**
 * 插入排序
 *
 * @author suchan
 * @date 2019/06/18
 */
public class InsertionSort {
    public void sort(int[] array) {
        if (array.length <= 1) {
            return;
        }

        for (int i = 1; i < array.length; i++) {
            int key = array[i];
            int j = i - 1;
            while (j >= 0 && array[j] > key) {
                array[j + 1] = array[j];
                j--;
            }
            array[j + 1] = key;
            // 或是下面这种写法
            /*
            for (int j = i - 1; j >= 0; j--) {
                if (array[j] > key) {
                    array[j + 1] = array[j];
                    array[j] = key;
                } else {
                    array[j + 1] = key;
                    break;
                }
            }
             */
        }
    }

    public static void main(String[] args) {
        int[] array = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        InsertionSort sort = new InsertionSort();
        sort.sort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.printf(array[i] + " ");
        }
    }
}
